import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_pink_app/composables/dynamic_row.dart';
import 'package:flutter_pink_app/serialized/profile.dart';
import 'package:flutter_pink_app/style/color.dart';
import 'package:flutter_pink_app/style/text.dart';
import 'package:flutter_pink_app/util.dart';
import 'package:url_launcher/url_launcher.dart';
import "../business/get_profile.dart";
import '../composables/profile_row.dart';
import "../composables/homepage_swiper.dart";
import "../composables/animate_card.dart";

// bili个人页面
class BiliPersonalPage extends StatefulWidget {
  final double expandedHeight; // 扩展高度
  final EdgeInsetsGeometry appbarPadding; // 状态栏内边距
  final double appbarHeight; // 状态栏高度

  const BiliPersonalPage(
      {Key key,
      this.appbarHeight,
      this.expandedHeight = 270,
      this.appbarPadding = const EdgeInsets.all(8)})
      : super(key: key); // 延申总高度
  @override
  _BiliPersonalPageState createState() => _BiliPersonalPageState();
}

class _BiliPersonalPageState extends State<BiliPersonalPage> {
  ProfileSerializedGen _profile = ProfileSerializedGen(); // 个人中心序列化数据
  ScrollController _sController = ScrollController(); // 滚动控制器
  TextStyle _currAppbarTextStyle = normalWhiteStyle;
  Map<String, String> _personalInfo = {
    '收藏': 'favorite',
    '点赞': 'like',
    '浏览': 'browsing',
    '硬币': 'coin',
    '粉丝': 'fans',
  };

  // 生命初始周期
  @override
  void initState() {
    super.initState();
    _initRequest();
    _sController.addListener(
        debounce(Duration(milliseconds: 200), _modifyAppbarTextStyle));
  }

  // 结束生命周期
  @override
  void dispose() {
    print("个人页销毁");
    _sController.dispose(); // 释放滚动控制器
    super.dispose();
  }

  // 修改顶部状态栏方法
  void _modifyAppbarTextStyle() {
    final style =
        _calculatePinProgress > 0.8 ? normalInputStyle : normalWhiteStyle;
    if (mounted && style != _currAppbarTextStyle) {
      setState(() {
        _currAppbarTextStyle = style;
      });
    }
  }

  // 计算滚动进度私有方法
  double get _calculatePinProgress {
    // 安全检测，需要保证控制器仍存在
    if (_sController == null || _sController.hasClients == false) return 0;
    final double totalPinPath = widget.expandedHeight - kToolbarHeight;
    final res = _sController.offset / totalPinPath;
    return res > 1 ? 1 : res;
  }

  // 初始化请求方法
  Future<void> _initRequest() async {
    final res = await getProfileInfo();
    if (res == null) {
      Timer(Duration(seconds: 3), _initRequest);// 3秒后发起轮循
      return;
    }
    if (mounted) {
      setState(() {
        _profile = res;
        _serializePersonInfo();
      });
    }
  }

  // 序列化个人信息
  void _serializePersonInfo() {
    _personalInfo["收藏"] = _profile.favorite.toString();
    _personalInfo["点赞"] = _profile.like.toString();
    _personalInfo["浏览"] = _profile.browsing.toString();
    _personalInfo["硬币"] = _profile.coin.toString();
    _personalInfo["粉丝"] = _profile.fans.toString();
  }

  // 构建头部栏
  SliverAppBar _buildAppbar() {
    return SliverAppBar(
        expandedHeight: widget.expandedHeight, // 扩展高度
        pinned: true,
        collapsedHeight: widget.appbarHeight,
        stretch: true, // 可以被拉伸
        flexibleSpace: FlexibleSpaceBar(
          title: _buildAvatar(),
          titlePadding: widget.appbarPadding,
          background: Image.asset(
            "images/banner.jpg",
            fit: BoxFit.cover,
            alignment: Alignment(0, -0.6), // 对齐中心靠上
          ),
        ));
  }

  // 构建头像
  Row _buildAvatar() {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(23),
          child: Image.asset("images/avatar.webp", width: 46, height: 46),
        ),
        Padding(
            padding: const EdgeInsets.only(left: 8.0),
            child: Text(_profile.name ?? "", style: _currAppbarTextStyle)),
      ],
    );
  }

  // 构建滚动区块标题
  Container _buildBodyTitle(String text, {IconData icon}) {
    return Container(
      padding: const EdgeInsets.fromLTRB(12, 12, 0, 6),
      child: Row(children: [
        Text(text, style: mainThemeStyle),
        if (icon != null)
          Padding(
            padding: const EdgeInsets.only(left: 4.0),
            child: Icon(
              icon,
              color: mainThemeColor,
              size: 16,
            ),
          )
      ]),
    );
  }

  // 构建番剧列表
  Widget _buildAnimationList(
      {double cardHeight = 214, double cardWidth = 160}) {
    return Wrap(
      alignment: WrapAlignment.spaceEvenly,
      runSpacing: 8,
      children: <Widget>[
        for (final AnimatedInfo animateInfo in _profile?.animatedList ?? [])
          AnimateCard(
            animateInfo,
            onTap: () => _launchUrl(animateInfo.url),
            height: cardHeight,
            width: cardWidth,
          )
      ],
    );
  }

  // 构建相关推荐栏
  Padding _buildBenenfitBar() {
    final benefitList = _profile.benefitList;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: DynamicShowRow(
        contentList:
            benefitList == null ? [] : benefitList.map((e) => e.name).toList(),
        cardHeight: 36,
        onClickCardCallback: (int index) => _launchUrl(benefitList[index].url),
        cardDecoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5), color: mainThemeColor),
      ),
    );
  }

  // 构建滚动内容区块
  SliverList _buildScrollBody() {
    final bannerList = _profile.bannerList ?? []; // 轮播图栏
    return SliverList(
        key: ValueKey("ScrollBody"),
        delegate: SliverChildListDelegate([
          ProfileRow(
              categoryMap: _personalInfo,
              rowMargin: const EdgeInsets.symmetric(horizontal: 20),
              rowDecoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: Colors.grey, width: 0.5)))),
          _buildBodyTitle("近期活动", icon: Icons.remove_red_eye),
          HomePageSwiper(bannerList.map((info) => info.cover).toList(),
              onTapped: (final index) => _launchUrl(bannerList[index].url),
              imgfit: BoxFit.fill,
              setPaginationShadow: true,
              isLoop: bannerList.length > 0, // 修复swiper的bug
              padding: const EdgeInsets.symmetric(horizontal: 12),
              height: 180),
          _buildBodyTitle("热播番剧", icon: Icons.video_library),
          _buildAnimationList(),
          _buildBodyTitle("相关推荐", icon: Icons.graphic_eq),
          _buildBenenfitBar()
        ]));
  }

  // 跳转URL方法
  Future<void> _launchUrl(String url) async {
    return await canLaunch(url)
        ? await launch(url)
        : throw 'Could not launch $url';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // 需要自定义滚动类别
        body: CustomScrollView(
      controller: _sController,
      physics: BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
      slivers: <Widget>[_buildAppbar(), _buildScrollBody()],
    ));
  }
}
